package com.john.apprssreader;

import java.io.IOException;

import javax.xml.parsers.ParserConfigurationException;

import org.xml.sax.SAXException;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.view.Menu;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ListView;
import android.widget.SimpleAdapter;
import android.widget.Toast;

import com.john.apprssreader.data.RssFeed;
import com.john.apprssreader.data.RssItem;
import com.john.apprssreader.util.RssFeedSAXParser;

public class MainActivity extends Activity implements OnItemClickListener {

	// RSS源
	private final String RSS_URL = "http://news.qq.com/newsgn/rss_newsgn.xml";

	public final String tag = "RSSReader";
	private RssFeed feed = null;

	private class DownloadWebpageTask extends AsyncTask<String, Void, String> {
		@Override
		protected String doInBackground(String... urls) {
			// params comes from the execute() call: params[0] is the url.
			try {
				return loadDtaFormUrl(urls[0]);
			} catch (IOException e) {
				return "无法连接到目标站点， URL可能非法。";
			}
		}

		// onPostExecute displays the results of the AsyncTask.
		@Override
		protected void onPostExecute(String result) {
			showListView();
		}
	}

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_main);

		ConnectivityManager connMgr = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
		NetworkInfo networkInfo = connMgr.getActiveNetworkInfo();
		if (networkInfo != null && networkInfo.isConnected()) {
			new DownloadWebpageTask().execute(RSS_URL);
		} else {
			Log.e(tag, "网络不可用");
			Toast.makeText(this, "网络不可用！", Toast.LENGTH_LONG).show();
		}
	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		// Inflate the menu; this adds items to the action bar if it is present.
		getMenuInflater().inflate(R.menu.main, menu);
		return true;
	}

	@Override
	public void onItemClick(AdapterView<?> parent, View view, int position,
			long id) {
		Intent intent = new Intent();
		intent.setClass(this, ShowDescriptionActivity.class);
		Bundle bundle = new Bundle();
		bundle.putString("title", feed.getItem(position).getTitle());
		bundle.putString("description", feed.getItem(position).getDescription());
		bundle.putString("link", feed.getItem(position).getLink());
		bundle.putString("pubdate", feed.getItem(position).getPubdate());
		// 用android.intent.extra.INTENT的名字来传递参数
		intent.putExtra("android.intent.extra.rssItem", bundle);
		startActivityForResult(intent, 0);
	}

	/*
	 * 把RSS内容绑定到ui界面进行显示
	 */
	private void showListView() {

		ListView itemList = (ListView) this.findViewById(R.id.itemlist);
		if (feed == null) {
			setTitle("访问的RSS无效");
			return;
		}
		SimpleAdapter simpleAdapter = new SimpleAdapter(this,
				feed.getAllItems(), android.R.layout.simple_list_item_2,
				new String[] { RssItem.TITLE, RssItem.PUBDATE }, new int[] {
						android.R.id.text1, android.R.id.text2 });
		itemList.setAdapter(simpleAdapter);
		itemList.setOnItemClickListener(this);
		itemList.setSelection(0);
	}

	/**
	 * do network
	 * 
	 * @param myurl
	 * @return
	 * @throws IOException
	 */
	private String loadDtaFormUrl(String myurl) throws IOException {
		try {
			feed = new RssFeedSAXParser().getFeed(RSS_URL);
			int count = feed.getAllItems().size();
			Log.d(tag, "获取到的数据条数为：" + count);
			System.out.println(feed.getAllItems());
			return feed.toString();
		} catch (ParserConfigurationException e) {
			e.printStackTrace();
			Log.e(tag, "ParserConfigurationException：rss解析失败");
		} catch (SAXException e) {
			e.printStackTrace();
			Log.e(tag, "ParserConfigurationException：rss解析失败");
		} catch (IOException e) {
			e.printStackTrace();
			Log.e(tag, "ParserConfigurationException：rss解析失败");
		}
		return null;
	}

}
